import pygame
from pygame.locals import *
from mastergoal.common.piece import *
from mastergoal.rules.ruleengine import RuleEngine
from mastergoal.rules.commonrules import CommonRules
from mastergoal.rules.level2rules import L2Rules
from util.vector import *
import os

class UIEvent:
    
    """ Handle all game events """
    
    def __init__(self, game):
        self.game = game
        self.piece_entity = None
    
    def __square_clicked(self,pos):
        """ Checks if square is selected """
        grid_coords = self.game.grid.get_position(pos)
        if grid_coords:
            key = str(grid_coords[0]) + '_' + str(grid_coords[1])
            self.sqr_selected = self.game.grid[key]
            self.square_tuple = grid_coords
            return grid_coords
        
        return None
    
    
    def __piece_clicked(self,pos):
        """ Checks if a piece is selected """
        for obj in self.game.pieces_gui:
            if obj.position.collidepoint(pos):
                self.piece_entity = obj
                return obj
        
        return None  
    
    def set_move_options(self, coords):
        
        piece_row, piece_col = self.game.grid.get_position(coords)
        key = str(piece_row) + '_' +str(piece_col)
        dest = self.game.grid[key]
        #print "Destination: " + str(self.game.grid["4_3"])
        self.piece_entity.destination = (dest.left, dest.top)
                
        piece_coords = self.piece_entity.get_coords()
                    
        self.piece_entity.move_delta = [ abs(piece_coords[i]-self.piece_entity.destination[i]) for i in range(2)]
        #print self.piece_entity.move_delta
                #exit()
        self.piece_entity.move_current = [0,0]
                    
        self.piece_entity.heading = Vector.from_points(piece_coords, self.piece_entity.destination)
        self.piece_entity.heading.normalise() * self.game.speed

                #print self.piece_entity.heading
        self.piece_entity.heading *= self.game.speed
                    
        self.piece_entity.moving = True
    
    
    def handle(self,event):
        """ Handle UI Events """
      
        # Save mouse coordinates
        coords = pygame.mouse.get_pos()
            
        # Piece clicked
        if self.__piece_clicked(coords):          
        # Check if a piece can be selected according to game state
            print self.piece_entity.piece
            
        # Square clicked    
        elif self.__square_clicked(coords):
                # 
            if self.piece_entity:
                    
                # Check rules before moving
                origin = (self.piece_entity.piece.square.row, self.piece_entity.piece.square.col)
                #destination = (self.game.grid.get_position(self.sqr_selected))
                destination = self.square_tuple
                
                #print destination
                
                ball_move = player_move = (False,None,None)
                    
                # What type of piece are we moving?
                try:
                    self.piece_entity.piece.id
                except AttributeError:
                    # Moving ball
                    ball_move = RuleEngine.valid_ball_movement(self.piece_entity.piece, destination, self.game.state)
                else:
                    # Moving piece
                    player_move = RuleEngine.valid_player_movement(self.piece_entity.piece, destination, self.game.state)
 
                # Apply moves
                # Check ball move
                # 0 - boolean
                # 1 - message
                # 2 - object 
                if ball_move[0]:
                     #ball_move[2].player_moving = self.game.state.player_with_ball
                     
                     if ball_move[1] == CommonRules.VALID_OK:
                         
                         self.game.state.do_move_ball(ball_move[2])
                         self.set_move_options(coords)
                         
                         self.game.state.player_with_ball = None
                         self.game.state.kicks = 0
                         
                     elif ball_move[1] == CommonRules.VALID_PASS:
                         
                         if self.game.state.kicks >= 3:
                             print CommonRules.desc_rules[CommonRules.INVALID_MAX_KICKS]
                             return CommonRules.INVALID_MAX_KICKS
                         
                         self.game.state.do_move_ball(ball_move[2])
                         self.set_move_options(coords)
                         
                         possible_players =  CommonRules.players_around_ball(self.game.state, ball_move[2])  
                         self.game.state.player_with_ball = possible_players[0]
                         self.game.state.kicks += 1
                         
                     else:
                        self.game.state.do_move_ball(ball_move[2])
                        self.set_move_options(coords)

                
                     
                # Check player response
                elif player_move[0]:
                    
                    self.game.state.do_move_player(player_move[2])
                    self.set_move_options(coords)
                    
                    if player_move[1] == CommonRules.VALID_REACHED_BALL:
                        self.game.state.player_with_ball = player_move[2].piece
                    
                     